<?php
require 'vendor/autoload.php';

class Printer {

	private $htmlCreator;
	private $arrayCleaner;
	private $configManager;
	private $textCleaner;

	function __construct($textCleaner, $htlmCreator, $textCleaner, $configManager) {
		$this->textCleaner = $textCleaner;
		$this->htmlCreator = $htlmCreator;
		$this->arrayCleaner = $textCleaner;
		$this->configManager = $configManager;
	}
	
	function printNews($news){

			$cnt = 0;
			$nroDePagina = 1;
			echo "<div class='acordeon'>";
			echo "<div class='pagina' id='pagina'>";
			$fuente ="";
			$huboCambioDeFuente = false;
			$link = $news->getLink();
			$shortName = $news->getShortName();
			$pubDate = $news->getPubDate();
			$titleNoHighlight = $news->getTitle();
			$titleWOUW = $this->arrayCleaner->removeUnwantedWords($titleNoHighlight);
			$titleWOUW = str_replace("'", "", $titleWOUW);
			$titulo = $news->getTitle();
			$resume = strip_tags($news->getResume());
			$newsHash = $news->getID();
			echo "<div class='newsContainer' name='news'>";
			echo "<h3>";
			echo"<div class='newsInfo'><a href='diario.php?diario=".$shortName."'><img src='img/logos/".$shortName.".png' width = '90' height = '25' style='float:left; border:none;' /></a></div>";
			echo "<p><a class='titulares'>" . $titulo ."</a></p></h3>";
			echo "<p><a class='descripcion'>" . $resume . "</a></p>";
			echo"<div class='newsTools'><div class='newsPubDate'>".$pubDate."</div></a></a>&nbsp;<a class='fancybox fancybox.iframe newsToolsFont' href='" . $link . "'>Ver noticia</a>  <a class='newsToolsFont'>|</a> <a class='newsToolsFont' href='buscar.php?keyword=" . $titleWOUW . "&ordenamiento=peso'>Buscar en Dengo</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href='https://twitter.com/intent/tweet?screen_name=dengoweb&text=$fuente:%20$titleNoHighlight&tw_p=tweetbutton'><img src='img/twitter.png' style='border:none;' title='Twittear'/></a> <a href='http://www.facebook.com/sharer.php?u=". $link ."' target='_blank'><img src='img/facebook.png' style='border:none;' title='Facebook'/></a></div>";
			echo "</div>";			
			echo "</div>";
			echo "</div>";
			
	}

	function printNewsToCompare($arrayNews,$keyword, $repeatedNews){

		$totalNews = count($arrayNews);
		$arrayNewsPerPage = 5;
		//la funcion ceil redondea hacia arriba.
		$pageAmount = ceil($totalNews / $arrayNewsPerPage);
		$idIndexSuperior = 1000;
		$idIndexInferior = 10000;
		if($totalNews > 0) {
			$cnt = 0;
			$nroDePagina = 1;
			echo "<div class='acordeon'>";
			echo "<div class='pagina' id='pagina'>";
			$fuente ="";
			$huboCambioDeFuente = false;
			foreach ($arrayNews as $news) {
				$link = $news->getLink();
				$shortName = $news->getShortName();
				$pubDate = $news->getPubDate();
				$titleNoHighlight = $news->getTitle();
				$titleWOUW = $this->arrayCleaner->removeUnwantedWords($titleNoHighlight);
				$titleWOUW = str_replace("'", "", $titleWOUW);
				$titulo = $news->getTitle();
				$titulo = $this->highlight($keyword,$news->getTitle());
				$resume = strip_tags($news->getResume());
				$resumenResaltado = $this->highlight($keyword,$resume);
				$newsHash = $news->getID();
				if ($newsHash != $repeatedNews->getID()) {
					if ($cnt < 6) {		
						echo "<div class='newsContainer' name='news'>";
					}else{
						if ($cnt == 6) {
							echo "<a id = 'begining'></a>";
						}
						echo "<div class='newsContainer' style='display:none' name='news'>";
					}
					echo "<h3>";
					echo"<div class='newsInfo'><a href='diario.php?diario=".$shortName."'><img src='img/logos/".$shortName.".png' width = '90' height = '25' style='float:left; border:none;' /></a></div>";
					echo "<p><a class='titulares'>" . $titulo ."</a></p></h3>";
					echo "<p><a class='descripcion'>" . $resumenResaltado . "</a></p>";
					echo"<div class='newsTools'><div class='newsPubDate'>".$pubDate."</div></a> <a class='newsToolsFont' href='comparar.php?firstNews=". $newsHash . "&keyword=" . $titleWOUW . "&ordenamiento=peso'>Comparar</a>&nbsp;<a class='newsToolsFont'>|</a>&nbsp;<a class='fancybox fancybox.iframe newsToolsFont' href='" . $link . "'>Ver noticia</a>  <a class='newsToolsFont'></a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href='https://twitter.com/intent/tweet?screen_name=dengoweb&text=$fuente:%20$titleNoHighlight&tw_p=tweetbutton'><img src='img/twitter.png' style='border:none;' title='Twittear'/></a> <a href='http://www.facebook.com/sharer.php?u=". $link ."' target='_blank'><img src='img/facebook.png' style='border:none;' title='Facebook'/></a></div>";
					echo "</div>";			
					$cnt++;
				}
			}
			echo "<img id='end' src='img/loading.gif' width='30' height='30' style='visibility:hidden' />";
			echo "</div>";
			echo "</div>";
		}else{
			echo "<div class='pagina' style='display:block'><div class='newsContainer'><a class='descripcion'>No se han encontrado resultados.</a></div></div>";
		}
	}
	
	
	function printNewsFromSearch($arrayNews,$keyword){

		$totalNews = count($arrayNews);
		$arrayNewsPerPage = 5;
		//la funcion ceil redondea hacia arriba.
		$pageAmount = ceil($totalNews / $arrayNewsPerPage);
		$idIndexSuperior = 1000;
		$idIndexInferior = 10000;
		if($totalNews > 0) {
			$cnt = 0;
			$nroDePagina = 1;
			echo "<div class='acordeon'>";
			echo "<div class='pagina' id='pagina'>";
			$fuente ="";
			$huboCambioDeFuente = false;
			foreach ($arrayNews as $news) {
				$link = $news->getLink();
				$shortName = $news->getShortName();
				$pubDate = $news->getPubDate();
				$titleNoHighlight = $news->getTitle();
				$titleWOUW = $this->arrayCleaner->removeUnwantedWords($titleNoHighlight);
				$titleWOUW = str_replace("'", "", $titleWOUW);
				$titulo = $this->highlight($keyword,$news->getTitle());
				$resume = strip_tags($news->getResume());
				$resumenResaltado = $this->highlight($keyword,$resume);
				$newsHash = $news->getID();
				$image = $news->getImage();
				if ($image != NULL) {
					$htmlImage = "<div style='float:left;display:inline-block;margin-right:10px'><img class='newsImage' src='$image' height='85'/></div>";
				}else{
					$htmlImage = "";
				}
				
				if ($cnt < 6) {		
					echo "<div class='newsContainer' name='news'>";
				}else{
					if ($cnt == 6) {
						echo "<a id = 'begining'></a>";
					}
					echo "<div class='newsContainer' style='display:none' name='news'>";
				}
				echo"<div class='newsInfo'><a href='diario.php?diario=".$shortName."'><img src='img/logos/".$shortName.".png' width = '90' height = '25' style='float:left; border:none;' /></a><br /><br /></div>";
				echo "<h3>";
				
				echo $htmlImage."<div style='text-align:left'><a class='titulares'>" . $titulo . "</a></div></h3>";
				echo "<p><a class='descripcion'>" . $resumenResaltado . "</a></p>";
				echo"<div class='newsTools'><div class='newsPubDate'>".$pubDate."</div></a> <a class='newsToolsFont' href='comparar.php?firstNews=". $newsHash . "&keyword=" . $titleWOUW . "&ordenamiento=peso'>Comparar</a>&nbsp;<a class='newsToolsFont'>|</a>&nbsp;<a class='fancybox fancybox.iframe newsToolsFont' href='" . $link . "'>Ver noticia</a>  <a class='newsToolsFont'>|</a> <a class='newsToolsFont' href='buscar.php?keyword=" . $titleWOUW . "&ordenamiento=peso'>Buscar la noticia en Dengo</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href='https://twitter.com/intent/tweet?screen_name=dengoweb&text=$fuente:%20$titleNoHighlight&tw_p=tweetbutton'><img src='img/twitter.png' style='border:none;' title='Twittear'/></a> <a href='http://www.facebook.com/sharer.php?u=". $link ."' target='_blank'><img src='img/facebook.png' style='border:none;' title='Facebook'/></a></div>";
				echo "</div>";			
				$cnt++;
			}
			echo "<img id='end' src='img/loading.gif' width='30' height='30' style='visibility:hidden' />";
			echo "</div>";
			echo "</div>";
		}else{
			echo "<div class='pagina' style='display:block'><div class='newsContainer'><a class='descripcion'>No se han encontrado resultados.</a></div></div>";
		}
	}

	function printAllNewsFromSource($noticias, $shortName){

		$totalDeNoticias = count($noticias);
		$noticiasPorPagina = 5;
		//la funcion ceil redondea hacia arriba.
		$cantidadDePaginas = ceil($totalDeNoticias / $noticiasPorPagina);
		$idIndexSuperior = 1000;
		$idIndexInferior = 10000;
		if($totalDeNoticias > 0) {
	
			$cnt = 0;
			$nroDePagina = 1;
			echo "<div class='acordeon'>";
			echo "<div class='pagina' id='pagina'>";
			foreach ($noticias as $noticia) {

				$link = $noticia->getLink();
				$titulo = $noticia->getTitle();
				$titleWOUW = $this->arrayCleaner->removeUnwantedWords($titulo);
				$titleWOUW = str_replace("'", "", $titleWOUW);
				$resume = $noticia->getResume();
				$pubDate = $noticia->getPubDate();
				$fuente = $noticia->getSource();
				$image = $noticia->getImage();
				if ($image != NULL) {
					$htmlImage = "<div style='float:left;display:inline-block;margin-right:10px'><img class='newsImage' src='$image' height='85'/></div>";
				}else{
					$htmlImage = "";
				}
				if ($cnt < 6) {		
					echo "<div class='newsContainer' name='news'>";
				}else{
					if ($cnt == 6) {
						echo "<a id = 'begining'></a>";
					}
					echo "<div class='newsContainer' style='display:none' name='news'>";
				}
				echo "<h3>";
				
				echo $htmlImage."<div style='text-align:left'><a class='titulares'>" . $titulo . "</a></div></h3>";
				echo "<p><a class='descripcion'>" . strip_tags($resume) . "</a></p>";
				echo"<div class='newsTools'><div class='newsPubDate'>".$pubDate."</div><a class='fancybox fancybox.iframe newsToolsFont' href='" . $link . "'>Ver noticia</a>  <a class='newsToolsFont'>|</a> <a class='newsToolsFont' href='buscar.php?keyword=" . $titleWOUW . "&ordenamiento=peso'>Buscar la noticia en Dengo</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href='https://twitter.com/intent/tweet?screen_name=dengoweb&text=$fuente:%20$titulo&tw_p=tweetbutton'><img src='img/twitter.png' style='border:none;' title='Twittear'/></a> <a href='http://www.facebook.com/sharer.php?u=". $link ."' target='_blank'><img src='img/facebook.png' style='border:none;' title='Facebook'/></a></div>";
				echo "</div>";			
				$cnt++;
			}
			echo "<img id='end' src='img/loading.gif' width='30' height='30' style='visibility:hidden' />";
			echo "</div>";
			echo "</div>";
			
		
		}else{
			echo "<div class='pagina' style='display:block;'><div class='newsContainer'><a class='descripcion'>En este momento se están actualizando los contenidos de este diario.<br /> Siga disfrutando del contenido del resto de las fuentes y reintente a la brevedad. </a></div></div>";
		}
	}

	function printTrendingNews(){
		/*
		 * Cuando dengo esta en el servidor, comentamos la 1era linea de codigo, y hacemos que
		 * createTrendingNewsFile, sea croneable cada x tiempo.
		 */
		//$this->htmlCreator->createTrendingNewsFile();
		$trendingNewsFile = file_get_contents('frontend/trendingNewsView.php', FILE_USE_INCLUDE_PATH);
		echo $trendingNewsFile;
	}

	function printTrendingWords(){
		/*
		 * Cuando dengo esta en el servidor, comentamos la 1era linea de codigo, y hacemos que
		 * createTrendingWordsFile, sea croneable cada x tiempo.
		 */
		//$this->htmlCreator->createTrendingWordsFile();
		$trendingWordsFile = file_get_contents('frontend/trendingWordsView.php', FILE_USE_INCLUDE_PATH);
		echo $trendingWordsFile;
	}

	function highlight($searchTerms, $text) {
		
		$wordsFromText = explode(" ", $text);
		$keysFromTerms = explode(" ",$searchTerms);
		$arrayKeys = array_unique($keysFromTerms);
		$arrayHighlighted = array();

		foreach($arrayKeys as $keyword){
			$key = $this->prepareKeyToHighlight($keyword);
			
			if(in_array($key, $this->configManager->getArticles())){
				
			}else{
				foreach($wordsFromText as $word){
					$auxWord = $this->prepareAuxWord($word);
					$auxText = $this->prepareAuxText($word);
					
					if(stripos($auxText,$key) !== FALSE){
						$kwLenght = strlen($key);
						$wordLenght = strlen($auxText);
						if ($kwLenght === $wordLenght && in_array($auxText, $arrayHighlighted) === FALSE){
							array_push($arrayHighlighted,$auxText);
							$text = preg_replace("/(".$auxWord.")/i","<span class='resaltado'>\\1</span>",$text);
						}
					}
				}
			}
		}
		return $text;
	}
	function prepareKeyToHighlight($keyword){
		$key = str_replace($this->configManager->getArrayCharacters(), "", $keyword);
		$key = $this->textCleaner->normalize($key);
		$key = strtolower($key);
		
		return $key;
	}
	
	function prepareAuxWord($word){
		$auxWord = str_replace($this->configManager->getArrayCharacters(), "", $word);
		//Expresion regular. Concateno \b al principio y final para determinar que
		//la palabra que buscamos empieza y termina donde corresponde.
		//ej: busco NO, que no encuentre BELGRANO.
		
		return $auxWord;
	}
	
	function prepareAuxText($word){
		$auxText = str_replace($this->configManager->getArrayCharacters(), "", $word);
		$auxText = $this->textCleaner->normalize($auxText);
		$auxText = strtolower($auxText);
		
		return $auxText;
	}
}